package com.ten.course.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ten.common.core.entity.*;
import com.ten.common.core.vo.Result;
import com.ten.course.dao.CourseCheckDao;
import com.ten.course.dao.CourseDescriptionDao;
import com.ten.course.dao.CourseListDao;
import com.ten.course.dao.CourseSubjectDao;
import com.ten.course.fegin.EduTeacherFeign;
import com.ten.course.fegin.TbMemberFeign;
import com.ten.course.service.CourseListService;
import com.ten.course.utils.CourseUtil;
import com.ten.course.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * @author ：张成（3092211427@qq.com）
 * @date ：Created in 2022/12/7 18:13
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class CourseListServiceImpl implements CourseListService {
    @Autowired
    private CourseListDao courseListDao;

    @Autowired
    private CourseSubjectDao courseSubjectDao;

    @Autowired
    private CourseDescriptionDao courseDescriptionDao;

    @Autowired
    private EduTeacherFeign eduTeacherFeign;

    @Autowired
    private CourseCheckDao courseCheckDao;

    @Autowired
    private TbMemberFeign tbMemberFeign;

    @Override
    public Result<Page<EduCourse>> findCourse(Integer pageCurrent, Integer pageSize, CourseCheckVo courseCheckVo) {
        Page<EduCourse> iPage = new Page<>(pageCurrent, pageSize);
        Page<EduCourse> iPage1 = courseListDao.findCourse(iPage, courseCheckVo);
        //根据课程名称查询出课程的分类
        List<EduCourse> courseList = iPage1.getRecords();
        List<EduSubject> eduSubjects = courseSubjectDao.selectList(null);
        List<EduSubject> treeEduSubjectList = CourseUtil.fromEduSubjectListToTreeEduSubjectList(eduSubjects);
        //对数据中的课程信息添加带有所属课程分类层级subjectName属性字段
        EduSubject eduSubject = new EduSubject();
        for (EduCourse eduCourse : courseList) {
            //返回树型位置中的EduSubject
            eduSubject = findOneself(eduSubject, treeEduSubjectList, eduCourse);
            StringBuilder sb = new StringBuilder();
            String subjectName = getSubjectName(eduSubject, sb).toString();
            eduCourse.setSubjectName(subjectName);
        }
        return new Result<>(200, "查询成功", iPage1);
    }

    /**
     * 根据课程分类父id来判断是否拼接下一个孩子字段
     *
     * @param eduSubject
     * @param sb
     * @return
     */
    private StringBuilder getSubjectName(EduSubject eduSubject, StringBuilder sb) {
        String stringBuilder = ("【") + eduSubject.getTitle() + "】";
        if (!eduSubject.getParentId().equals("0")) {
            EduSubject eduSubject1 = courseSubjectDao.selectById(eduSubject.getParentId());
            sb = getSubjectName(eduSubject1, sb);
            sb.append(" >");
        }
        return sb.append(stringBuilder);
    }

    /**
     * 根据eduCourse查询出普通的eduSubject所在树型结构中位置中的eduSubject
     *
     * @param eduSubject
     * @param treeEduSubjectList
     * @param eduCourse
     * @return
     */
    private EduSubject findOneself(EduSubject eduSubject, List<EduSubject> treeEduSubjectList, EduCourse eduCourse) {
        for (EduSubject subject : treeEduSubjectList) {
            if (subject.getId().equals(eduCourse.getSubjectId())) {
                return subject;
            } else {
                List<EduSubject> children = subject.getChildren();
                eduSubject = findOneself(eduSubject, children, eduCourse);
            }
        }
        return eduSubject;
    }

    /**
     * 根据课程id修改课程的status（上下架）
     *
     * @param listChangeStatusVo 相关属性
     * @return
     */
    @Transactional
    @Override
    public Result changeStatus(ListChangeStatusVo listChangeStatusVo) {
        EduCourse eduCourse = courseListDao.selectById(listChangeStatusVo.getId());
        eduCourse.setStatus(listChangeStatusVo.getStatus());
        //修改status根据id
        int i = courseListDao.updateById(eduCourse);
        if (i > 0) {
            return new Result(200, "修改成功");
        }
        return new Result(500, "修改失败");
    }

    /**
     * 根据课程id修改课程的信息
     *
     * @param courseChangeVo 课程列表和课程审核进行修改的Vo类
     * @return
     */
    @Transactional
    @Override
    public Result updateCourse(CourseChangeVo courseChangeVo) {
        EduCourse eduCourse = null;
        CourseDescription courseDescription = null;
        if (courseChangeVo.getId() != null) {
            eduCourse = courseListDao.selectById(courseChangeVo.getId());
            courseDescription = courseDescriptionDao.selectById(courseChangeVo.getId());
        } else {
            eduCourse = courseListDao.selectById(courseChangeVo.getCourseId());
            courseDescription = courseDescriptionDao.selectById(courseChangeVo.getCourseId());
        }
        //设置课程详情表中的详情内容
        courseDescription.setDescription(courseChangeVo.getDescription());
        int update = courseDescriptionDao.updateById(courseDescription);
        //设置课程表中的内容
        eduCourse.setTitle(courseChangeVo.getTitle());
        eduCourse.setPrice(courseChangeVo.getPrice());

        int i = courseListDao.updateById(eduCourse);
        if (i > 0 && update > 0) {
            return new Result(200, "修改成功");
        }
        return new Result(500, "修改失败");
    }

    @Override
    public Result<Boolean> updateIsAdd(EduCourse eduCourse) {
        int res = courseListDao.updateById(eduCourse);
        if (res > 0) {
            return new Result<>(200, "修改成功", true);
        }
        return new Result<>(500, "修改失败", false);
    }


    /*************************客户端service*********************/


    /**
     * 根据老师的手机号查询该老师下的所有的课程信息
     *
     * @param pageCurrent   当前页数
     * @param pageSize      每页显示的行数
     * @param teacherMobile 老师的手机号
     * @param checkStatus   课程审核的状态
     * @return
     */
    @Override
    public Result<IPage<EduCourse>> getCourseByTeacherPhone(Integer pageCurrent, Integer pageSize, String teacherMobile, String checkStatus) {
        IPage<EduCourse> iPage = new Page<>(pageCurrent, pageSize);
        //根据老师的手机号查询出老师的相关信息，然后利用老师id进行关联查询
        Result<EduTeacher> eduTeacher = eduTeacherFeign.getTeacherByMobile(teacherMobile);
        String id = eduTeacher.getData().getId();
        IPage<EduCourse> iPage1 = courseListDao.getCourseByTeacherPhone(iPage, id, checkStatus);
        return new Result<>(200, "查询成功", iPage1);
    }

    /**
     * 根据前端传过来的信息，根据课程id对课程信息，包括课程的分类和描述等进行修改
     * 也可以对课程进行添加
     *
     * @param updateCourseSubjectVo 更新课程信息Vo类
     * @return
     */
    @Transactional
    @Override
    public Result updateCourseSubject(UpdateCourseSubjectVo updateCourseSubjectVo) {
        //UpdateCourseSubjectVo(id=1408410746248617986, title=Java核心技术-典型案例与面试实战系列二(SpringBoot2.0+企业真实案例）, price=0.0, description=<p>光阴似箭、岁月如梭</p><p>转眼间已至2020年末</p><p>想到这一年发生的糟心事</p><p>不由得感慨万千、思绪横飞</p><p>而IT互联网内卷依旧</p><p>竞争依旧激烈、就业环境依旧严酷</p><p>因此，巩固自身核心竞争力</p><p>扎实自身技术根基 势在必行！！！</p>, categoryId1=1315829265286197250, categoryId2=1315829265416220674, categoryId3=1603660336998424577, cover=https://kk-books.oss-cn-hangzhou.aliyuncs.com/94b126c1-3aa9-469c-9397-693e9c84254b.jpg, remark=)
        //1.对课程表进行修改
        UpdateWrapper<EduCourse> uw1 = new UpdateWrapper<>();
        //如果存在id，则是修改
        if (StringUtils.hasText(updateCourseSubjectVo.getId())) {
            uw1.eq("id", updateCourseSubjectVo.getId());
            uw1.set("title", updateCourseSubjectVo.getTitle());
            uw1.set("price", updateCourseSubjectVo.getPrice());
            uw1.set("cover", updateCourseSubjectVo.getCover());
            uw1.set("remark", updateCourseSubjectVo.getRemark());
            uw1.set("gmt_modified", LocalDateTime.now());
            uw1.set("status", "Draft");
            if (StringUtils.hasText(updateCourseSubjectVo.getCategoryId3())) {
                uw1.set("subject_parent_id", updateCourseSubjectVo.getCategoryId2());
                uw1.set("subject_id", updateCourseSubjectVo.getCategoryId3());
            } else if (StringUtils.hasText(updateCourseSubjectVo.getCategoryId2())) {
                uw1.set("subject_parent_id", updateCourseSubjectVo.getCategoryId1());
                uw1.set("subject_id", updateCourseSubjectVo.getCategoryId2());
            } else {
                uw1.set("subject_parent_id", "0");
                uw1.set("subject_id", updateCourseSubjectVo.getCategoryId1());
            }
            int update = courseListDao.update(null, uw1);
            //2.对课程描述表进行修改
            UpdateWrapper<CourseDescription> uw2 = new UpdateWrapper<>();
            uw2.eq("id", updateCourseSubjectVo.getId());
            uw2.set("description", updateCourseSubjectVo.getDescription());
            int i = courseDescriptionDao.update(null, uw2);
            //3.修改课程的相关内容后，应当重新进行审核
            UpdateWrapper<CheckCourse> uw3 = new UpdateWrapper<>();
            uw3.eq("course_id", updateCourseSubjectVo.getId());
            uw3.set("check_status", "2");
            int update1 = courseCheckDao.update(null, uw3);
            if (i > 0 && update > 0 && update1 > 0) {
                return new Result(200, "课程修改成功");
            }
        } else {
            //如果不存在id，则是添加
            //使用hutool工具生成一个随机id
            //1.添加课程信息到课程表中
            long id = IdUtil.getSnowflakeNextId();
            EduCourse eduCourse = new EduCourse();
            eduCourse.setId(id + "");
            eduCourse.setRemark(updateCourseSubjectVo.getRemark());
            eduCourse.setPrice(updateCourseSubjectVo.getPrice());
            eduCourse.setTitle(updateCourseSubjectVo.getTitle());
            eduCourse.setCover(updateCourseSubjectVo.getCover());
            eduCourse.setRemark(updateCourseSubjectVo.getRemark());
            eduCourse.setIsAdd(0);
            if (StringUtils.hasText(updateCourseSubjectVo.getCategoryId3())) {
//                说明该课程所在的分类有3层
                eduCourse.setSubjectParentId(updateCourseSubjectVo.getCategoryId2());
                eduCourse.setSubjectId(updateCourseSubjectVo.getCategoryId3());
            } else if (StringUtils.hasText(updateCourseSubjectVo.getCategoryId2())) {
                //说明该课程所在的分类有2层
                eduCourse.setSubjectParentId(updateCourseSubjectVo.getCategoryId1());
                eduCourse.setSubjectId(updateCourseSubjectVo.getCategoryId2());
            } else {
                //说明该课程所在的分类就是一层
                eduCourse.setSubjectParentId("0");
                //设置父分类
                eduCourse.setSubjectId(updateCourseSubjectVo.getCategoryId1());
            }
            Result<EduTeacher> teacherByMobile = eduTeacherFeign.getTeacherByMobile(updateCourseSubjectVo.getMobile());
            String teacherId = teacherByMobile.getData().getId();
            eduCourse.setTeacherId(teacherId);
            int insert = courseListDao.insert(eduCourse);
            //2.设置课程描述表中的内容
            CourseDescription courseDescription = new CourseDescription();
            courseDescription.setId(id + "");
            courseDescription.setDescription(updateCourseSubjectVo.getDescription());
            int i = courseDescriptionDao.insert(courseDescription);
            //3.在课程审核表中添加课程的相关信息
            CheckCourse checkCourse = new CheckCourse();
            checkCourse.setCourseId(id + "");
            int insert1 = courseCheckDao.insert(checkCourse);
            if (insert > 0 && i > 0 && insert1 > 0) {
                return new Result(200, "课程添加成功", eduCourse);
            }
        }
        return new Result(500, "操作失败");
    }


    /**
     * 提供feign的远程调用
     */
    //通过课程id查询课程信息
    @Override
    public Result<List<EduCourse>> selectByCourseId(String courseId) {
        List<EduCourse> list = new ArrayList<>();
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("id", courseId);
//        wrapper.eq("is_deleted", 0);
        EduCourse eduCourse = courseListDao.selectById(courseId);
        System.out.println(courseId);
        if (eduCourse != null) {
            list.add(eduCourse);
            return new Result<>(2000, "查询信息成功", list);
        }
        return null;
    }

    /**
     * 根据fontFindCourseVo中包含的课程分类id来查询里面所含有的课程信息
     *
     * @param pageCurrent      当前页码
     * @param pageSize         显示条数
     * @param fontFindCourseVo 包含课程分类id和isFree信息
     * @return
     */
    @Override
    public Result<Page<EduCourse>> fontFindCourse(Integer pageCurrent, Integer pageSize, FontFindCourseVo fontFindCourseVo) {
        Page<EduCourse> page = new Page<>(pageCurrent, pageSize);
        Page<EduCourse> page1 = courseListDao.fontFindCourse(page, fontFindCourseVo);
        return new Result(200, "查询成功", page1);
    }

    /**
     * 根据课程id查询课程和教师信息
     *
     * @param id 课程id
     * @return
     */
    @Override
    public Result<CourseTeacherVo> queryAllCoursesAndTeacherName(String id) {
        CourseTeacherVo courseTeacherVo = new CourseTeacherVo();
        EduCourse eduCourse = courseListDao.selectById(id);
        courseTeacherVo.setTeacherId(eduCourse.getTeacherId());
        courseTeacherVo.setPrice(eduCourse.getPrice());
        courseTeacherVo.setIsFree(eduCourse.getPrice() == 0);
        courseTeacherVo.setTitle(eduCourse.getTitle());
        courseTeacherVo.setCover(eduCourse.getCover());
        courseTeacherVo.setBuyCount(eduCourse.getBuyCount());
        courseTeacherVo.setViewCount(eduCourse.getViewCount());
        //查询课程描述信息
        CourseDescription courseDescription = courseDescriptionDao.selectById(eduCourse.getId());
        courseTeacherVo.setDescription(courseDescription.getDescription());
        //根据老师id查询老师的信息
        Result<EduTeacher> teacher = eduTeacherFeign.getTeacherById(eduCourse.getTeacherId());
        courseTeacherVo.setIntro(teacher.getData().getIntro());
        courseTeacherVo.setName(teacher.getData().getName());
        courseTeacherVo.setAvatar(teacher.getData().getAvatar());
        return new Result<>(200, "查询成功", courseTeacherVo);
    }

    /**
     * 根据手机号查询该视频信息是该讲师发布的
     *
     * @param courseId
     * @param mobile
     * @return
     */
    @Override
    public Result queryAllById(String courseId, String mobile) {
        //根据手机号查询老师信息
        Result<EduTeacher> result = eduTeacherFeign.getTeacherByMobile(mobile);
        EduTeacher teacher = result.getData();
        if (teacher != null) {
            EduCourse eduCourse = courseListDao.selectById(courseId);
            if (eduCourse.getTeacherId().equals(teacher.getId())) {
                return new Result(200, "该视频是该老师发布的");
            }
            return new Result(500, "该视频是不是该老师发布的");
        }
        return new Result(500, "该会员不是老师，需要购买视频");
    }

    /**
     * 根据课程id和会员id判断当前账号是否为讲师
     *
     * @param courseId
     * @param huiYuanId
     * @return
     */
    @Override
    public Result<TbMember> queryMemberStatus(String courseId, String huiYuanId) {
        EduCourse eduCourse = courseListDao.selectById(courseId);
        //根据判断会员手机号与该课程的老师的手机号是否相同来判断该会员是否为讲师
        Result<EduTeacher> result = eduTeacherFeign.getTeacherById(eduCourse.getTeacherId());
        EduTeacher teacher = result.getData();
        System.out.println(teacher);
        Result<TbMember> memberByMobile = tbMemberFeign.getMemberByMobile(teacher.getMobile());
        TbMember data = memberByMobile.getData();
        System.out.println(data);
        if (memberByMobile.getData() != null) {
            return new Result(200, "该会员是讲师", memberByMobile.getData());
        }
        return new Result<>(500, "该会员不是讲师", null);
    }

    @Override
    public Result<Page<EduCourse>> findCourseByTeacherId(Integer pageCurrent, Integer pageSize, CourseGuanZhuVo courseGuanZhuVo) {
        Page<EduCourse> page = new Page<>(pageCurrent,pageSize);
        Page<EduCourse> page1 = courseListDao.findCourseByTeacherId(page,courseGuanZhuVo);
        return new Result<>(200,"查询成功",page1);
    }

    /**
     * 查询出前台专区中应该显示的课程有哪些，供首页微服务进行调用
     * @return
     */
    @Override
    public Result<List<EduCourse>> getCoursesByConditions() {
        List<EduCourse> list = courseListDao.getCoursesByConditions();
        return new Result<>(200,"查询成功",list);
    }

    /**
     * 将专区中可以添加的数据都展现出来，供首页服务进行调用
     * @param pageCurrent
     * @param pageSize
     * @param courseCheckVo
     * @return
     */
    @Override
    public Result<Page<EduCourse>> getAllDetail(Integer pageCurrent, Integer pageSize, CourseCheckVo courseCheckVo) {
        Page<EduCourse> page =new Page<>(pageCurrent,pageSize);
        Page<EduCourse> page1 = courseListDao.getAllDetail(page,courseCheckVo);
        List<EduCourse> courseList = page1.getRecords();
        List<EduSubject> eduSubjects = courseSubjectDao.selectList(null);
        List<EduSubject> treeEduSubjectList = CourseUtil.fromEduSubjectListToTreeEduSubjectList(eduSubjects);
        //对数据中的课程信息添加带有所属课程分类层级subjectName属性字段
        EduSubject eduSubject = new EduSubject();
        for (EduCourse eduCourse : courseList) {
            //返回树型位置中的EduSubject
            eduSubject = findOneself(eduSubject, treeEduSubjectList, eduCourse);
            StringBuilder sb = new StringBuilder();
            String subjectName = getSubjectName(eduSubject, sb).toString();
            eduCourse.setSubjectName(subjectName);
        }
        return new Result<>(200,"查询成功",page1);
    }


}